package com.core.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.log4j.Logger;

public class DspConnection {
	
	static Logger logger = Logger.getLogger(DspUtil.Log4J);

	private static DataSource ds = null;
	
	public static Connection getConnection() throws SQLException{
		if (ds == null) {
			init();
		}
		return ds.getConnection();
	}
	
	/**
	 * 关闭数据连接
	 * @param connection
	 */
	public static void closeConnection(Connection connection){
		try {
			if (connection != null && !connection.isClosed()){
				connection.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			
		}
	}
	
	public static void closeConnection(PreparedStatement pstmt , Connection connection){
		try {
			if (pstmt != null) {
				pstmt.close();
			}
			closeConnection(connection);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 初始化数据源
	 */
	private static void init(){
		Connection conn = null;
		try {
			ds =  (DataSource)DspUtil.getBean("dataSource");
			ds.getConnection();
			conn = ds.getConnection();
			logger.debug(" 数据库连接成功....");
		} catch (SQLException e) {
			e.printStackTrace();
		}  finally {
			closeConnection(conn);
		}
	}
	/**
	 * 执行删除操作
	 * @param sql
	 * @return
	 */
	public static boolean delete (String sql){
		Connection connection = null;
		PreparedStatement pstmt = null;
		try {
			connection = getConnection();
			pstmt = connection.prepareStatement(sql);
			pstmt.execute();
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			closeConnection(pstmt , connection);
		}
		return false;
	}
}
